﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DAL;

namespace Arbetsfornedringen.Pages
{
    public partial class Admin : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                Session["CurrentOption"] = (int)AuthorityLevel.User;
            BindGridView();
            DeleteExpired.Text = String.Format("Ta bort utgångna annonser ({0})", AdDB.GetExpiredAdsCount());
        }

        protected void ShowUsers_Click(object sender, EventArgs e)
        {
            BindGridView(AuthorityLevel.User);
        }

        protected void ShowHeadHunters_Click(object sender, EventArgs e)
        {
            BindGridView(AuthorityLevel.HeadHunter);
        }

        private void BindGridView(AuthorityLevel level)
        {
            GridViewAccount.DataSource = AccountDB.GetAccounts(level)
                            .Select(a => new
                            {
                                AccountId = a.AccountId,
                                CompleteName = a.ContactInformation == null ? "#": a.ContactInformation.CompleteName,
                                Email = a.Email,
                                PhoneNumber = a.ContactInformation == null ? "#": a.ContactInformation.PhoneNumber
                            });

            GridViewAccount.DataBind();
            Session["CurrentOption"] = (int)level;
        }

        private void BindGridView()
        {
            var lastLevel = (int)Session["CurrentOption"];

            if (lastLevel == (int)AuthorityLevel.User || lastLevel == (int)AuthorityLevel.HeadHunter)
                BindGridView((AuthorityLevel) lastLevel);
        }

        protected void GridViewAccount_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {

        }

        protected void GridViewAccount_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var index = e.RowIndex;
            var s = sender as GridView;
            var accountIdString = s.Rows[index].Cells[0].Text;
            var accountId = int.Parse(accountIdString);
            System.Diagnostics.Debug.Print(accountId.ToString());

            AccountDB.DeleteAccount(accountId);
            BindGridView();
        }

        protected void ShowAddUser_Click(object sender, EventArgs e)
        {
            Response.Redirect("AdminRegisterAccount.aspx");
        }

        protected void DeleteExpired_Click(object sender, EventArgs e)
        {
            AdDB.DeleteExpiredAds();
            DeleteExpired.Text = String.Format("Ta bort utgångna annonser ({0})", AdDB.GetExpiredAdsCount());
        }
    }
}